package com.example.chessbattleplatform.utils;

import cn.hutool.json.JSONUtil;
import com.example.chessbattleplatform.Pojo.Result.WebResult;
import com.example.chessbattleplatform.Pojo.Result.websocketResult;
import com.example.chessbattleplatform.Pojo.WebSocketSessionIdAndUserId;
import jakarta.websocket.Session;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Getter
@Slf4j
public class WebSocketSessionSendMessage {

    /**
     * 存储所有的session
     * key: sessionId
     * value: WebSocketSessionIdAndUserId
     */
    private final Map<String, WebSocketSessionIdAndUserId> sessionMap = new HashMap<>();

    // 添加
    public WebSocketSessionIdAndUserId addSessionMap(Session session, WebSocketSessionIdAndUserId webSocketSessionIdAndUserId) {
        return sessionMap.put(session.getId(), webSocketSessionIdAndUserId);
    }

    // 删除
    public WebSocketSessionIdAndUserId deleteSessionMap(Session session) {
        return sessionMap.remove(session.getId());
    }


    // 获取 Session id 并 发送消息(Json)
    public void sendSuccessMessage(Object message, Session session) {
        sendSuccessMessage(message, session.getId());
    }

    // 使用指定的 Session id 并 发送消息(Json)
    public void sendSuccessMessage(Object message, String sessionId) {
        websocketResult<Object> success = websocketResult.success(message);
        String string = JSONUtil.toJsonStr(success);
        log.info("session_Id Json 发送消息:{}", string);
        sessionMap.get(sessionId).getSession().getAsyncRemote().sendText(string);
    }

}
